﻿using ColemanDevelopment.Utilities.Parsers.Xml;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ColemanSoftware.Delicious.Modules.Data
{
    internal static class DeliciousResultsParser
    {

        /// <summary>
        /// Parses the results provided by Delicious API system
        /// the results will be provided in XML format.
        /// </summary>
        /// <param name="results">The results.</param>
        /// <returns></returns>
        public static List<XmlData> ParseResults(string results)
        {
            List<XmlData> data = new List<XmlData>();

            if (results != null)
                data = XmlParser.ParseXml(results).ToList();

            return data;
        }

        public static string ParseResultCode(string results)
        {
            string returnData = "";
            List<XmlData> xmlData = new List<XmlData>();

            if (results != null)
                xmlData = XmlParser.ParseXml(results).ToList();

            if (xmlData.Any())
            {
                returnData = ParseError(xmlData);
            }

            return returnData;
        }

        /// <summary>
        /// Parses the error.
        /// </summary>
        /// <param name="dataToGetErrors">The data to get errors.</param>
        /// <returns></returns>
        public static string ParseError(List<XmlData> dataToGetErrors)
        {
            string error = "";

            // Make sure we have data
            if (dataToGetErrors != null && dataToGetErrors.Count != 0)
            {
                var resultXml = dataToGetErrors.Where(xml => xml.ElementName == "result");

                foreach (var d in resultXml)
                {
                    AttributePair attr = d.Attributes.SingleOrDefault(x => x.Name == "code");
                    // Were there errors?
                    if (attr != null)
                        error = attr.Value;
                }
            }

            return error;
        }


    }
}
